package cn.wei.sdd.rabbitutils.service;

import cn.wei.sdd.rabbitutils.constant.MQConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: wei
 * @Date: 2022/01/24/15:50
 */
@Service
@Slf4j
public class MQService {
    @Resource
    private AmqpTemplate amqpTemplate;

    /**
     *  发送消息
     * @param exchange 交换机
     * @param routingKey 路由
     * @param message 消息
     */
    public boolean sendMessage(String exchange,String routingKey,Object message){
        log.info("发送消息");
        amqpTemplate.convertAndSend(exchange, routingKey, message);
        return true;
    }

    /**
     * 发送订单消息
     * @param message
     * @param dateTime
     */
    public void sendOrder(String message,Integer dateTime){
        log.info("发送延时队列,当前时间：{}，延迟队列编号：{},延时时间：{},",
                LocalDateTime.now(),message,new SimpleDateFormat("mm").format(new Date(dateTime)));
        amqpTemplate.convertAndSend(
                MQConst.DELAY_EXCHANGE_ORDER,
                MQConst.DELAY_ROUTING_ORDER,
                message,
                msg->{
                    //设置消息的到期时间
                    msg.getMessageProperties().setDelay(dateTime);

                    return msg;
                }
        );

    }
}
